package algorithm.easy;

import java.util.Arrays;

public class Solution67 {
    // 输入: a = "1010", b = "1011"
    //输出: "10101"
    public static String addBinary(String a, String b) {
        char[] sc = new char[Math.max(a.length(),b.length())+1];
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<Math.abs(a.length()-b.length());i++){
            sb.append("0");
        }
        if(a.length()>b.length()){
            b += sb.toString();
        }else{
            a += sb.toString();
        }
        char[] ac = a.toCharArray();
        char[] bc = b.toCharArray();
        int acl = ac.length-1;
        int bcl = bc.length-1;
        int scl = sc.length-1;
        int carryFlag = 0;
        while(scl>0){
            if(carryFlag==1){
                if(ac[acl]=='1' && bc[bcl]=='1'){
                    sc[scl] = '1';
                    carryFlag = 1;
                }else if(ac[acl]=='1' || bc[bcl]=='1'){
                    sc[scl] = '0';
                    carryFlag = 1;
                }else{
                    sc[scl] = '1';
                    carryFlag = 0;
                }
            }else{
                if(ac[acl]=='1' && bc[bcl]=='1'){
                    sc[scl] = '0';
                    carryFlag = 1;
                }else if(ac[acl]=='1' || bc[bcl]=='1'){
                    sc[scl] = '0';
                    carryFlag = 0;
                }else{
                    sc[scl] = '0';
                    carryFlag = 0;
                }
            }
            if(carryFlag==1){
                sc[0] = '1';
            }
            acl--;
            bcl--;
            scl--;
        }

        System.out.println(Arrays.toString(sc));
        return Arrays.toString(sc);

    }

    public static void main(String[] args){
        String a = "1111", b = "1";
        System.out.println(addBinary(a,b));
    }
}
